package org.alexisjago.footballmanager.domain;

import java.util.Date;
import java.util.HashSet;
import java.util.Set;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;

@Entity
@Table(name ="event")
public class Match {
	
	@Column(name = "matchDate")
	private Date matchDate;
	
	@ManyToMany
	@JoinTable(name = "unallocated_player", joinColumns = {@JoinColumn(name = "eventId", referencedColumnName = "id")}
	            ,
	            inverseJoinColumns = @JoinColumn( name= "playerID", referencedColumnName= "id"))
	private Set<Player> unallocatedPlayers;
	
	@OneToOne
	@JoinColumn(name = "team1")
	private Team team1;
	
	@OneToOne
	@JoinColumn(name = "team2")
	private Team team2;
	
	@Id  
    @GeneratedValue  
	private int ID;

	public Match(Date matchDate){
		this();
		this.matchDate = matchDate;
	}

	public Match(){
		unallocatedPlayers = new HashSet<Player>();
		team1 = new Team("Whites");
		team2 = new Team("Colours");
	}
	
	public void resetTeams(){
		unallocatedPlayers.addAll(team1.getPlayers());
		unallocatedPlayers.addAll(team2.getPlayers());
		team1.getPlayers().clear();
		team2.getPlayers().clear();
	}
	
	public void addPlayerToTeam1(Player player){
		
		if(unallocatedPlayers.remove(player)){
			team1.getPlayers().add(player);
		}
		else if(team2.getPlayers().remove(player)){
			team1.getPlayers().add(player);
		}
		else{
			throw new RuntimeException("Player not found");
		}
	}
	
	public void addPlayerToTeam2(Player player){
		
		if(unallocatedPlayers.remove(player)){
			team2.getPlayers().add(player);
		}
		else if(team1.getPlayers().remove(player)){
			team2.getPlayers().add(player);
		}
		else{
			throw new RuntimeException("Player not found");
		}
	}
	
	public void unallocatePlayer(Player player){
		if(team1.getPlayers().remove(player)){
			unallocatedPlayers.add(player);
		}
		else if(team2.getPlayers().remove(player)){
			unallocatedPlayers.add(player);
		}
		else{
			throw new RuntimeException("Player not found");
		}
	}

	public Date getMatchDate() {
		return matchDate;
	}

	public void setMatchDate(Date matchDate) {
		this.matchDate = matchDate;
	}

	public Set<Player> getUnallocatedPlayers() {
		return unallocatedPlayers;
	}

	public void setUnallocatedPlayers(Set<Player> unallocatedPlayers) {
		this.unallocatedPlayers = unallocatedPlayers;
	}

	public Team getTeam1() {
		return team1;
	}

	public void setTeam1(Team team1) {
		this.team1 = team1;
	}

	public Team getTeam2() {
		return team2;
	}

	public void setTeam2(Team team2) {
		this.team2 = team2;
	}
	
	public int getID() {
		return ID;
	}

	public void setID(int iD) {
		ID = iD;
	}
}
